<template>
  <div class="yard-plan-container">
    <!-- 标题栏 -->
    <div class="page-title">
      <div class="left-section">
        <h1>计划管理</h1>
        <!-- 移动机组选择按钮到标题栏左侧 -->
        <div class="title-unit-selector">
          <q-btn
            :class="['unit-btn', {'unit-btn-selected': selectedUnit === 'LT1'}]"
            color="white"
            label="连退机组"
            @click="changeUnit('LT1')"
            flat
          />
          <q-btn
            :class="['unit-btn', {'unit-btn-selected': selectedUnit === 'TZ1'}]"
            color="white"
            label="脱脂机组"
            @click="changeUnit('TZ1')"
            flat
          />
          <q-btn
            :class="['unit-btn', {'unit-btn-selected': selectedUnit === 'DG1'}]"
            color="white"
            label="镀铬机组"
            @click="changeUnit('DG1')"
            flat
          />
          <q-btn
            :class="['unit-btn', {'unit-btn-selected': selectedUnit === 'DX1'}]"
            color="white"
            label="镀锡机组"
            @click="changeUnit('DX1')"
            flat
          />
        </div>
      </div>
    </div>

    <!-- 左侧面板 -->
    <div class="panel left-panel">
      <div class="panel-header">
        <div class="title-wrapper">
          <span class="title-text">待上料</span>
        </div>
      </div>
      <div class="search-area">
        <div class="search-row">
          <q-btn
            label="刷新"
            color="primary"
            @click="fetchPendingFeedData"
            :loading="isLoading"
            class="refresh-btn"
          />
          <q-input
            v-model="searchQuery"
            label="模糊搜索"
            dense
            outlined
            class="search-input"
            @update:model-value="handleSearch"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <q-btn
            v-if="false"
            color="primary"
            label="库位解锁"
            @click="handleUnlock"
            class="unlock-btn"
          />
          <q-btn
            v-if="false"
            color="primary"
            label="车离"
            @click="handleCarLeave"
            class="car-leave-btn"
          />
          
          <!-- 移除区域号下拉框和坐标赋值按钮 -->
      <!--    <div class="saddle-info">
            {{ saddleNo }}：{{ matNo }}
          </div> -->
        </div>
      </div>

      <!-- 左侧数据列表 -->
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th class="checkbox-col"></th>
              <th>设备号</th>
              <th>计划号</th>
              <th>材料号</th>
              <th>计划状态</th>
              <th>库位</th>
              <th>层号</th>
            </tr>
          </thead>
          <tbody>
            <template v-if="pendingFeedList.length > 0">
              <tr v-for="(item, index) in pendingFeedList" :key="index">
                <td><q-checkbox v-model="item.selected" /></td>
                <td>{{item.produceEquNo}}</td>
                <td>{{item.planNo}}</td>
                <td>{{item.matNo}}</td>
                <td>{{getPlanStatusText(item.planStatus)}}</td>
                <td>{{item.stockNo || '-'}}</td>
                <td>{{item.layer || '-'}}</td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 中间控制按钮 -->
    <div class="controls">
      <q-btn
        icon="chevron_right"
        color="primary"
        @click="moveToRight"
        :disable="leftSelectedItems.length === 0 || feedingStatus === '上料开始'"
      />
      <q-btn
        icon="chevron_left"
        color="primary"
        @click="moveToLeft"
        :disable="rightSelectedItems.length === 0 || feedingStatus === '上料开始'"
      />
    </div>

    <!-- 右侧面板 -->
    <div class="panel right-panel">
      <div class="panel-header">
        <div class="title-wrapper">
          <span class="title-text">已确认上料顺</span>
        </div>
      </div>
      <div class="action-buttons">
        <q-btn
          color="primary"
          label="确定上料顺"
          @click="handleConfirmProduction"
          class="action-btn"
        />
        <q-btn
          color="positive"
          label="上料开始"
          @click="handleStartFeeding"
          class="action-btn"
          :disable="feedingStatus !== '上料暂停' || rightPendingList.length === 0"
        />
        <q-btn
          color="warning"
          label="上料暂停"
          @click="handlePauseFeeding"
          class="action-btn"
          :disable="feedingStatus === '上料暂停'"
        />
        <div class="status-text">
          上料状态：<span :class="{ 
            'status-pause': feedingStatus === '上料暂停',
            'status-start': feedingStatus === '上料开始'
          }">{{ feedingStatus }}</span>
        </div>
        <div class="unit-status">
          机组状态：
          <span :class="{
            'status-error': unitStatus === '故障',
            'status-occupied': unitStatus === '占用',
            'status-idle': unitStatus === '空闲'
          }">{{ unitStatus }}</span>
        </div>
      </div>
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th class="checkbox-col"></th>
              <th>生产设备号</th>
              <th>计划号</th>
              <th>材料号</th>
              <th>计划状态</th>
              <th>库位号</th>
            </tr>
          </thead>
          <tbody>
            <template v-if="rightPendingList.length > 0">
              <tr 
                v-for="(item, index) in rightPendingList" 
                :key="index"
                :draggable="item.planStatus < 22 && (feedingStatus === '上料暂停' || feedingStatus === '上料未开始')"
                @dragstart="dragStart($event, index)"
                @dragover.prevent
                @dragenter.prevent
                @drop="drop($event, index)"
                :class="{ 
                  'dragging': draggedIndex === index,
                  'not-draggable': item.planStatus >= 22 || (feedingStatus !== '上料暂停' && feedingStatus !== '上料未开始')
                }"
              >
                <td>
                  <q-checkbox 
                    v-model="item.selected" 
                    :disable="item.planStatus >= 22"
                  />
                </td>
                <td>{{item.produceEquNo}}</td>
                <td>{{item.planNo}}</td>
                <td>{{item.matNo}}</td>
                <td>
                  <span :class="{
                    'status-normal': item.planStatus < 22,
                    'status-in-progress': item.planStatus === 22,
                    'status-completed': item.planStatus > 22
                  }">
                    {{getPlanStatusText(item.planStatus)}}
                  </span>
                </td>
                <td>{{item.stockNo || '-'}}</td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
// 使用普通的 script 定义组件名
export default {
  name: 'YardPlan'
}
</script>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { get, post } from 'src/boot/api'
import { useQuasar } from 'quasar'
import { useWebsocket } from 'src/pages/_sys/use-websocket1'

const $q = useQuasar()

// 添加当前选中的机组
const selectedUnit = ref('LT1') // 默认为连退机组

// 切换机组的方法
const changeUnit = async (unit: string) => {
  if (selectedUnit.value === unit) return
  
  selectedUnit.value = unit
  saddleNo.value = `${unit}_02` // 更新鞍座号
  
  // 刷新所有数据
  await Promise.all([
    fetchPendingFeedData(),
    fetchRightPendingData(),
    getFeedingStatus()
  ])
}

// 计划选项数据
const planOptions = ref([
  { label: '计划A', value: 'A' },
  { label: '计划B', value: 'B' },
  { label: '计划C', value: 'C' }
])

// 选中的计划
const selectedPlan = ref(null)

// 过滤后的选项
const filteredOptions = ref([...planOptions.value])

// 搜索相关
const searchQuery = ref('')

// 左侧数据
const leftItems = ref([
  { id: 1, name: '项目1', description: '描述1' },
  { id: 2, name: '项目2', description: '描述2' },
  { id: 3, name: '项目3', description: '描述3' }
])

// 右侧数据
const rightItems = ref([])

// 选中项
const leftSelectedItems = computed(() => {
  return pendingFeedList.value.filter(item => item.selected)
})

const rightSelectedItems = computed(() => {
  return rightPendingList.value.filter(item => item.selected)
})

// 待上料数据
const pendingFeedList = ref([])

// 右侧数据列表
const rightPendingList = ref([])

// 添加加载状态
const isLoading = ref(false)

// 添加原始数据的备份
const originalPendingFeedList = ref([])

// 计划状态映射
const planStatusMap = {
  1: '初始化',
  11: '待备料',
  12: '备料中',
  14: '计划过期',
  15: '备料已完成',
  21: '计划指令已选中',
  22: '材料已预约',
  23: '执行中',
  24: '已上料',
  30: '完成',
  32: '计划暂停',
  '-1': '异常'
}

// 状态转换函数
const getPlanStatusText = (status: number) => {
  return planStatusMap[status] || `未知状态(${status})`
}

// 上料状态
const feedingStatus = ref('')

// 获取上料状态
const getFeedingStatus = async () => {
  try {
    const response = await get('/productionByHmi/getProductionStatus', {
      unitNo: selectedUnit.value
    })
    
    feedingStatus.value = response || ''
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: '获取上料状态失败'
    })
  }
}

const fetchPendingFeedData = async () => {
  isLoading.value = true
  try {
    const response = await get('/productionByHmi/getProductionDetailByPlanType', {
      planType: 'ORD',
      unitNo: selectedUnit.value
    })
   
    if (Array.isArray(response)) {
      const data = response.map(item => ({
        ...item,
        selected: false
      }))
      pendingFeedList.value = data
      originalPendingFeedList.value = data // 保存原始数据
    } else {
      throw new Error('返回数据格式不正确')
    }
  } catch (error) {
    console.error('获取待上料数据失败:', error)
    $q.notify({
      type: 'negative',
      message: '获取待上料数据失败'
    })
  } finally {
    isLoading.value = false
  }
}

// 获取右侧数据
const fetchRightPendingData = async () => {
  try {
    const response = await get('/productionByHmi/getProductionInfo', {
      planType: selectedUnit.value
    })
    
    if (Array.isArray(response)) {
      rightPendingList.value = response.map(item => ({
        ...item,
        selected: false
      }))
    } else {
      throw new Error('返回数据格式不正确')
    }
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: '获取已确认上料顺失败'
    })
  }
}

// 添加机组状态
const unitStatus = ref('空闲')

// 添加 saddleNo 和 matNo 的响应式变量
const saddleNo = ref('LT1_02')  // 设置默认值
const matNo = ref('')

// 加入记忆状态，减少不必要的DOM更新
const prevUnitStatus = ref('');
const prevMatNo = ref('');

// 进一步优化 handleYlkUnitInfo 函数
const handleYlkUnitInfo = (data: any) => {
  try {
    // 获取当前机组数据
    const unitData = data?.[selectedUnit.value]?.unitLoop;
    
    if (!Array.isArray(unitData) || unitData.length === 0) return;
    
    // 查找当前机组的两个鞍座
    const saddle01 = unitData.find((item: any) => item.saddleNo === `${selectedUnit.value}_01`);
    const saddle02 = unitData.find((item: any) => item.saddleNo === `${selectedUnit.value}_02`);
    
    // 检查鞍座状态
    let newStatus = '空闲';
    
    // 都占用就是占用
    if (saddle01 && saddle02 && saddle01.occupy === '1' && saddle02.occupy === '1') {
      newStatus = '占用';
    }
    // 有一个故障就是故障
    else if ((saddle01 && saddle01.error === '1') || (saddle02 && saddle02.error === '1')) {
      newStatus = '故障';
    } 
    // 其他情况为空闲
    
    // 只有在状态变化时才更新 DOM
    if (prevUnitStatus.value !== newStatus) {
      unitStatus.value = newStatus;
      prevUnitStatus.value = newStatus;
    }
    
    // 更新当前选中鞍座的物料号
    const currentSaddle = unitData.find((item: any) => item.saddleNo === saddleNo.value);
    if (currentSaddle) {
      const newMatNo = currentSaddle.matNo || '';
      if (prevMatNo.value !== newMatNo) {
        matNo.value = newMatNo;
        prevMatNo.value = newMatNo;
      }
    }
  } catch (error) {
    console.error('Error processing YLK_UNIT_INFO:', error);
  }
}

// 进一步优化 WebSocket 消息处理，增加节流时间
let lastWebSocketHandleTime = 0;
const throttleDelay = 500; // 增加到500毫秒

// 加入防抖变量
let pendingWebSocketData = null;
let webSocketUpdateTimer = null;

const handleWebSocketMessage = async (payload: { topic: string; data: any }) => {
  try {
    switch (payload.topic) {
      case 'EQUIMENT_DEAIL_UPDATE':
        console.log('Equipment detail update received:', payload);
        // 收到消息后刷新所有数据
        await Promise.all([
          fetchPendingFeedData(),
          fetchRightPendingData(),
          getFeedingStatus()
        ]);
        break;
        
      case 'YLK_UNIT_INFO':
        // 保存最新数据
        pendingWebSocketData = payload.data;
        
        // 添加节流和防抖逻辑
        const now = Date.now();
        if (now - lastWebSocketHandleTime > throttleDelay) {
          // 清除任何未执行的计时器
          if (webSocketUpdateTimer) {
            clearTimeout(webSocketUpdateTimer);
          }
          
          // 立即处理数据并重置时间戳
          handleYlkUnitInfo(pendingWebSocketData);
          lastWebSocketHandleTime = now;
          pendingWebSocketData = null;
        } else {
          // 设置一个计时器，在节流时间后执行最新数据
          if (webSocketUpdateTimer) {
            clearTimeout(webSocketUpdateTimer);
          }
          
          webSocketUpdateTimer = setTimeout(() => {
            if (pendingWebSocketData) {
              handleYlkUnitInfo(pendingWebSocketData);
              lastWebSocketHandleTime = Date.now();
              pendingWebSocketData = null;
            }
          }, throttleDelay);
        }
        break;
        
      default:
        console.log('Received message with different topic:', payload.topic);
    }
  } catch (error) {
    console.error('Error processing WebSocket message:', error);
  }
}

// 修改 WebSocket 订阅
useWebsocket('EQUIMENT_DEAIL_UPDATE,YLK_UNIT_INFO', handleWebSocketMessage)

// 添加定时器引用
let autoCheckTimer: NodeJS.Timer | null = null

// 添加自动检查函数
const autoCheckAndConfirm = async () => {
  try {
    if (rightPendingList.value.length === 0 && feedingStatus.value === '上料开始') {
      // 直接发送确认请求，不弹出对话框
      const response = await post(`/productionByHmi/confirmProduction?planType=ORD&equNo=${selectedUnit.value}`, {
        data: []  // 空数组，因为rightPendingList为空
      })
      
      await Promise.all([
        getFeedingStatus(),
        fetchRightPendingData()
      ])
    }
  } catch (error) {
    console.error('自动确认上料顺序失败:', error)
  }
}

// 在 onMounted 中启动定时器
onMounted(() => {
  // 初始化数据
  Promise.all([
    fetchPendingFeedData(),
    fetchRightPendingData(),
    getFeedingStatus()
  ])

  // 启动定时器，每4秒检查一次
  autoCheckTimer = setInterval(autoCheckAndConfirm, 4000)
})

// 在 onUnmounted 中清除定时器
onUnmounted(() => {
  if (autoCheckTimer) {
    clearInterval(autoCheckTimer)
    autoCheckTimer = null
  }
})

// 搜索处理
const handleSearch = (val: string) => {
  if (!val.trim()) {
    // 如果搜索框为空，恢复原始数据
    pendingFeedList.value = [...originalPendingFeedList.value]
    return
  }

  const searchValue = val.toLowerCase().trim()
  pendingFeedList.value = originalPendingFeedList.value.filter(item => {
    return (
      (item.produceEquNo?.toLowerCase().includes(searchValue)) ||
      (item.planNo?.toLowerCase().includes(searchValue)) ||
      (item.matNo?.toLowerCase().includes(searchValue)) ||
      (item.stockNo?.toLowerCase().includes(searchValue)) ||
      (item.layer?.toString().includes(searchValue))
    )
  })
}

// 移动数据方法
const moveToRight = () => {
  if (feedingStatus.value === '上料开始') {
    return
  }

  // 获取左侧选中的项目
  const selectedItems = pendingFeedList.value.filter(item => item.selected)
  
  if (selectedItems.length === 0) return

  // 添加到右侧列表，但重置selected状态
  rightPendingList.value = [
    ...rightPendingList.value, 
    ...selectedItems.map(item => ({
      ...item,
      selected: false // 重置选中状态
    }))
  ]
  
  // 从左侧列表移除
  pendingFeedList.value = pendingFeedList.value.filter(item => !item.selected)
  
  // 更新原始数据
  originalPendingFeedList.value = pendingFeedList.value
}

const moveToLeft = () => {
  if (feedingStatus.value === '上料开始') {
    return
  }

  // 获取右侧选中的项目，过滤掉状态 >= 22 的项目
  const selectedItems = rightPendingList.value.filter(item => 
    item.selected && item.planStatus < 22
  )
  
  if (selectedItems.length === 0) return

  // 添加到左侧列表，但重置selected状态
  pendingFeedList.value = [
    ...pendingFeedList.value, 
    ...selectedItems.map(item => ({
      ...item,
      selected: false // 重置选中状态
    }))
  ]
  
  // 从右侧列表移除
  rightPendingList.value = rightPendingList.value.filter(item => !item.selected || item.planStatus >= 22)
  
  // 更新原始数据
  originalPendingFeedList.value = pendingFeedList.value
}

const handleUnlock = async () => {
  try {
    await get('/t11', { areaNo: '' })
    $q.notify({
      type: 'positive',
      message: '解锁成功',
      timeout: 2500
    })
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: '库位解锁请求失败'
    })
  }
}

const handleCarLeave = async () => {
  try {
    await post('AS01/carStatusChange', {
      data: {
        parkingNo: 'PC1',
        action: -121
      }
    })
    $q.notify({
      type: 'positive',
      message: '车离成功',
      timeout: 2500
    })
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: '车离请求失败'
    })
  }
}

const handleStartFeeding = async () => {
  try {
    $q.dialog({
      title: '确认',
      message: '确定要开始上料吗？',
      cancel: true,
      persistent: true
    }).onOk(async () => {
      await post(`/productionByHmi/feedingOrderStart?unitNo=${selectedUnit.value}&planType=ORD`, {
       
      })
      $q.notify({
        type: 'positive',
        message: '上料开始',
        timeout: 2500
      })
      await Promise.all([
        getFeedingStatus(),
        fetchRightPendingData()
      ])
    })
  } catch (error) {
    console.error('上料开始失败:', error)
    $q.notify({
      type: 'negative',
      message: '上料开始失败'
    })
  }
}

const handlePauseFeeding = async () => {
  try {
    $q.dialog({
      title: '确认',
      message: '确定要暂停上料吗？',
      cancel: true,
      persistent: true
    }).onOk(async () => {
      await post(`/productionByHmi/feedingOrderPause?unitNo=${selectedUnit.value}`, {
       
      })
      $q.notify({
        type: 'positive',
        message: '上料已暂停',
        timeout: 2500
      })
      await Promise.all([
        getFeedingStatus(),
        fetchRightPendingData()
      ])
    })
  } catch (error) {
    console.error('上料暂停失败:', error)
    $q.notify({
      type: 'negative',
      message: '上料暂停失败'
    })
  }
}

const handleConfirmProduction = async () => {
  try {
    $q.dialog({
      title: '确认',
      message: '确定要确认上料顺序吗？',
      cancel: true,
      persistent: true
    }).onOk(async () => {
      // 在发送请求前，根据当前顺序设置 executeNumber
      const dataWithExecuteNumber = rightPendingList.value.map((item, index) => ({
        ...item,
        executeNumber: index + 1  // 从1开始的顺序值
      }))

      await post(`/productionByHmi/confirmProduction?planType=ORD&equNo=${selectedUnit.value}`, {
        data: dataWithExecuteNumber
      })
      
      $q.notify({
        type: 'positive',
        message: '确认上料顺序成功',
        timeout: 2500
      })
      await Promise.all([
        getFeedingStatus(),
        fetchRightPendingData()
      ])
    })
  } catch (error) {
    console.error('确认上料顺序失败:', error)
    $q.notify({
      type: 'negative',
      message: '确认上料顺序失败'
    })
  }
}

// 添加拖拽相关的状态
const draggedIndex = ref(-1)

// 拖拽开始时的处理函数
const dragStart = (event: DragEvent, index: number) => {
  const item = rightPendingList.value[index]
  
  if (item.planStatus >= 22 || feedingStatus.value === '上料开始') {
    event.preventDefault()
    return
  }

  draggedIndex.value = index
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/plain', index.toString())
  }
}

// 放置时的处理函数
const drop = async (event: DragEvent, dropIndex: number) => {
  event.preventDefault()
  const dragIndex = draggedIndex.value
  
  if (
    dragIndex === dropIndex || 
    rightPendingList.value[dragIndex].planStatus >= 22 ||
    rightPendingList.value[dropIndex].planStatus >= 22 ||
    (feedingStatus.value !== '上料暂停' && feedingStatus.value !== '上料未开始')
  ) {
    draggedIndex.value = -1
    return
  }
  
  // 获取拖拽的项目
  const draggedItem = rightPendingList.value[dragIndex]
  
  // 从数组中移除拖拽的项目
  rightPendingList.value.splice(dragIndex, 1)
  
  // 在新位置插入项目
  rightPendingList.value.splice(dropIndex, 0, draggedItem)
  
  // 重置拖拽索引
  draggedIndex.value = -1
}

// 添加计算属性判断是否允许移动操作
const isMovementAllowed = computed(() => {
  // 只有在上料暂停或未开始时允许操作
  return feedingStatus.value === '上料暂停' || feedingStatus.value === '上料未开始'
})
</script>

<style scoped lang="scss">
.yard-plan-container {
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  padding: 20px;
  height: 100vh;
  width: 100%;
  gap: 20px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5; // 整体背景色

  .page-title {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    background-color: #1976d2;
    color: white;
    padding: 0 20px;
    display: flex;
    align-items: center;

    .left-section {
      display: flex;
      align-items: center;
    }

    h1 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
      margin-right: 20px;
    }
    
    // 标题栏内的机组选择器
    .title-unit-selector {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
      
      .unit-btn {
        font-weight: 500;
        font-size: 14px;
        height: 36px;
        border-radius: 4px;
        color: #1976d2 !important; // 未选中按钮的文字颜色为蓝色
        background-color: white !important; // 未选中按钮背景为白色
        
        &:hover {
          background-color: rgba(255, 255, 255, 0.85) !important;
        }
      }
      
      .unit-btn-selected {
        background-color: #4caf50 !important; // 选中按钮的背景颜色改为绿色，与"上料开始"按钮相同
        color: white !important; // 选中按钮的文字颜色为白色
      }
    }
  }
  
  .panel {
    margin-top: 50px; // 恢复原来的顶部间距
    flex: 1;
    display: flex;
    flex-direction: column;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    padding: 16px;
    background: white; // 面板背景设为白色

    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 48px;
      margin-bottom: 16px;
      border-bottom: 2px solid #1976d2;

      .title-wrapper {
        display: flex;
        align-items: center;
        
        .title-text {
          font-size: 16px;
          font-weight: 500;
          color: #1976d2;
        }
      }
    }

    .search-area {
      height: auto;  // 修改为自适应高度
      margin-bottom: 16px;

      .search-row {
        display: flex;
        gap: 8px;
        align-items: center;
        flex-wrap: wrap; // 允许元素换行

        .refresh-btn {
          min-width: 40px;
        }

        .search-input {
          width: 250px;
        }

        .unlock-btn,
        .car-leave-btn {
          margin-left: 8px;
        }
        
        .saddle-info {
          margin-left: 16px;
          display: inline-flex;
          align-items: center;
          font-size: 20px;
          font-weight: bold;
          color: #000000;
          white-space: nowrap;
          padding: 8px 0;
          height: 40px;
          line-height: 40px;
          min-width: fit-content;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .table-container {
      flex: 1;
      overflow: auto;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      background: white;
      
      .data-table {
        width: 100%;
        border-collapse: collapse;
        
        th, td {
          padding: 12px 8px;
          text-align: left;
          border-bottom: 1px solid #e0e0e0;
          white-space: nowrap;
        }
        
        th {
          background: #f5f5f5;
          font-weight: 500;
          color: #666;
        }
        
        .checkbox-col {
          width: 48px;
          text-align: center;
        }
        
        tr {
          cursor: move;
          transition: background-color 0.2s;
          
          &.dragging {
            opacity: 0.5;
            background-color: #e0e0e0;
          }
          
          &.not-draggable {
            cursor: not-allowed;
            opacity: 0.7;
            background-color: #f5f5f5;
          }
          
          &:hover {
            background-color: #f5f5f5;
          }
        }
        
        tr:last-child td {
          border-bottom: none;
        }
      }
    }

    .action-buttons {
      display: flex;
      gap: 8px;
      margin-bottom: 16px;  // 添加底部间距

      .action-btn {
        min-width: 85px;
      }
    }
  }

  .controls {
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 16px;
    padding: 10px;
    margin-top: 50px;
  }
}

.right-panel {
  .action-buttons {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    align-items: center;
    flex-wrap: wrap; // 允许元素换行

    .action-btn {
      min-width: 85px;
    }

    .status-text {
      margin-left: 16px;
      font-size: 20px;
      font-weight: bold;
      color: #000000;
      
      span {
        font-weight: bold;
        font-size: 20px;

        &.status-pause {
          color: #FFD700; // 黄色
        }

        &.status-start {
          color: #008000; // 绿色
        }
        
        // 新增上料未开始状态的样式
        &:not(.status-pause):not(.status-start) {
          color: #8B0000; // 黑红色
        }
      }
    }
    
    .unit-status {
      margin-left: 16px;
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: bold;
      color: #000000;
      
      span {
        font-weight: bold;
        margin-left: 4px;
        font-size: 20px;
        
        &.status-error {
          color: #ff0000; // 红色表示故障
        }
        
        &.status-occupied {
          color: #ffa500; // 橙色表示占用
        }
        
        &.status-idle {
          color: #008000; // 绿色表示空闲
        }
      }
    }
  }

  .table-container {
    // 使用与左侧相同的表格样式
    @extend .table-container;
  }
}

.not-draggable {
  cursor: not-allowed !important;
  opacity: 0.7;
  background-color: #f5f5f5;
}

.data-table {
  .status-normal {
    // 保持原有样式
  }

  .status-in-progress {
    color: #008000; // 绿色
    font-weight: bold;
  }

  .status-completed {
    color: #8B0000; // 黑红色
    font-weight: bold;
  }
}
</style>